package com.jpro.module.system.service.notify;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.common.pojo.PageResult;
import com.jpro.framework.security.config.SecurityProperties;
import com.jpro.module.system.cache.CacheService;
import com.jpro.module.system.controller.admin.notify.vo.message.NotifyMessageMyPageReqVO;
import com.jpro.module.system.controller.admin.notify.vo.message.NotifyMessagePageReqVO;
import com.jpro.module.system.dal.dataobject.notify.NotifyMessageDO;
import com.jpro.module.system.dal.dataobject.notify.NotifyTemplateDO;
import com.jpro.module.system.dal.mysql.notify.NotifyMessageMapper;
import com.jpro.module.system.enums.logger.LoginLogTypeEnum;
import com.jpro.module.system.service.auth.AdminAuthService;
import com.jprocms.module.cms.api.GlobalConfigApi;
import com.jprocms.module.cms.api.dto.GlobalConfigRespVO;
import com.jprocms.module.cms.api.dto.SecurityConfig;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static com.jpro.framework.security.core.util.SecurityFrameworkUtils.obtainAuthorization;
import static com.jpro.module.system.dal.redis.RedisKeyConstants.USER_LAST_OPEREATE;

/**
 * 站内信 Service 实现类
 *
 * @author xrcoder
 */
@Service
@Validated
public class NotifyMessageServiceImpl implements NotifyMessageService {

    @Resource
    private NotifyMessageMapper notifyMessageMapper;
    @Resource
    private GlobalConfigApi globalConfigApi;
    @Resource
    private CacheService cacheService;
    @Resource
    private SecurityProperties securityProperties;
    @Resource
    private AdminAuthService authService;

    @Override
    public Long createNotifyMessage(Long userId, Integer userType,
                                    NotifyTemplateDO template, String templateContent, Map<String, Object> templateParams) {
        NotifyMessageDO message = new NotifyMessageDO().setUserId(userId).setUserType(userType)
                .setTemplateId(template.getId()).setTemplateCode(template.getCode())
                .setTemplateType(template.getType()).setTemplateNickname(template.getNickname())
                .setTemplateContent(templateContent).setTemplateParams(templateParams).setReadStatus(false);
        notifyMessageMapper.insert(message);
        return message.getId();
    }

    @Override
    public PageResult<NotifyMessageDO> getNotifyMessagePage(NotifyMessagePageReqVO pageReqVO) {
        return notifyMessageMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<NotifyMessageDO> getMyMyNotifyMessagePage(NotifyMessageMyPageReqVO pageReqVO, Long userId, Integer userType) {
        return notifyMessageMapper.selectPage(pageReqVO, userId, userType);
    }

    @Override
    public NotifyMessageDO getNotifyMessage(Long id) {
        return notifyMessageMapper.selectById(id);
    }

    @Override
    public List<NotifyMessageDO> getUnreadNotifyMessageList(Long userId, Integer userType, Integer size) {
        return notifyMessageMapper.selectUnreadListByUserIdAndUserType(userId, userType, size);
    }

    @Override
    public Long getUnreadNotifyMessageCount(Long userId, Integer userType) {
        final CommonResult<GlobalConfigRespVO> globalConfigResp = globalConfigApi.getGlobalConfig();
        if (globalConfigResp.isSuccess()) {
            final GlobalConfigRespVO globalConfigRespVO = globalConfigResp.getData();
            final SecurityConfig securityConfig = globalConfigRespVO.getSecurityConfig();
            //是否开启长时间未操作自动退出账号 ApiAccessLogInterceptor 设置最后访问时间
            String cacheKey = USER_LAST_OPEREATE + ":" + userId;
            final Object lastOpeTime = cacheService.getCacheObject(cacheKey);
            if (securityConfig.isInactivityLogoutEnable() && securityConfig.getInactivityLogoutTime() > 0 && lastOpeTime != null) {
                Long lastOperateTimeLong = (Long) lastOpeTime;
                // 转换成Instant
                Instant instant = Instant.ofEpochMilli(lastOperateTimeLong);
                // 转换成LocalDateTime
                LocalDateTime lastOperateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

                final long lastOpeMinute = LocalDateTimeUtil.between(lastOperateTime, LocalDateTimeUtil.now(), ChronoUnit.MINUTES);
                if (lastOpeMinute >= securityConfig.getInactivityLogoutTime()) {
                    //强制退出账号
                    ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                    String token = obtainAuthorization(sra.getRequest(), securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
                    if (StrUtil.isNotBlank(token)) {
                        cacheService.deleteObject(cacheKey);
                        authService.logout(token, LoginLogTypeEnum.LOGOUT_DELETE.getType());
                    }
                }
            }
        }
        return notifyMessageMapper.selectUnreadCountByUserIdAndUserType(userId, userType);
    }

    @Override
    public int updateNotifyMessageRead(Collection<Long> ids, Long userId, Integer userType) {
        return notifyMessageMapper.updateListRead(ids, userId, userType);
    }

    @Override
    public int updateAllNotifyMessageRead(Long userId, Integer userType) {
        return notifyMessageMapper.updateListRead(userId, userType);
    }

}
